package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_splash

import android.annotation.SuppressLint
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.PopupMenu
import android.widget.Toast
import com.anythink.core.api.ATDebuggerConfig
import com.anythink.core.api.ATGDPRAuthCallback
import com.anythink.core.api.ATSDK
import com.anythink.core.api.DeviceDataInfo.GAID
import com.anythink.core.api.NetTrafficeCallback
import com.anythink.network.admob.AdmobATConst.DEBUGGER_CONFIG.Admob_NETWORK
import com.anythink.network.applovin.ApplovinATConst.DEBUGGER_CONFIG.Applovin_NETWORK
import com.anythink.network.bigo.BigoATConst.DEBUGGER_CONFIG.BigoAds_NETWORK
import com.anythink.network.inmobi.InmobiATConst.DEBUGGER_CONFIG.Inmobi_NETWORK
import com.anythink.network.ironsource.IronsourceATConst.DEBUGGER_CONFIG.Ironsource_NETWORK
import com.anythink.network.mintegral.MintegralATConst.DEBUGGER_CONFIG.Mintegral_NETWORK
import com.anythink.network.pangle.PangleATConst.DEBUGGER_CONFIG.Pangle_NETWORK
import com.anythink.network.unityads.UnityAdsATConst.DEBUGGER_CONFIG.UnityAds_NETWORK
import com.anythink.network.vungle.VungleATConst.DEBUGGER_CONFIG.Vungle_NETWORK
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.BuildConfig
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.model.GoogleMobileAdsConsentManager
import com.bp.hearthealth.pulse.lnapps.ads.model.PreloadAds
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.SplashAdShowActivity
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.TopOnOpenAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.listener.ad_action.TopOnOpenAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.SplashType
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObservable
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.observer.TopOnSplashFinishObserver
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyer
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.BpBloodPressureNewRecordActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_guide.BpHeartRateGuideActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_language.BpLanguageViewModel
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.guide.GuideSplashActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.LaunchTypeDetector
import com.bp.hearthealth.pulse.lnapps.bp_utils.ProgressBarUpdater
import com.bp.hearthealth.pulse.lnapps.bp_utils.SpUtils
import com.bp.hearthealth.pulse.lnapps.databinding.ActivitySplashBgBinding
import com.bp.hearthealth.pulse.lnapps.firbase.FireBaseUtils
import com.google.android.gms.ads.MobileAds
import com.mbridge.msdk.MBridgeConstans
import com.mbridge.msdk.MBridgeSDK
import com.mbridge.msdk.out.MBridgeSDKFactory
import com.vungle.ads.VunglePrivacySettings
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Objects
import java.util.concurrent.atomic.AtomicBoolean


@SuppressLint("CustomSplashScreen")
class BpSplashActivity : BpBaseActivity<ActivitySplashBgBinding>(), TopOnSplashFinishObserver {

    private var adOpenLaunch: Boolean = true//冷启动广告是否开
    private var isColdLaunch: Boolean = true//是否冷启动
    private var listener: Boolean = true
    lateinit var progressBarUpdater: ProgressBarUpdater
    private var firstShow: String? = null
    private val viewMode: BpLanguageViewModel by viewModel()
    private var dismissUMP = false
    private var afChannel = false //true：af返回了归因结果
    private var initTopOn = false //true：已经初始化过，并且加载了广告

    override fun initListener() {
        super.initListener()
//        initAdInfo()
        initAppsFlyer()
        initTopOn()
//        LogUtil.i("启动页 初始化 ${System.currentTimeMillis()}")
        isColdLaunch = LaunchTypeDetector.isColdStart()
        LogUtil.i("冷启动： $isColdLaunch")
        adOpenLaunch = AdsSwitch.getBoolean(AdsSwitch.adOpenLaunch)
        LogUtil.i("第一次冷启动后_开屏广告是否展示：$adOpenLaunch")
        firstShow = SpUtils.getString(Constants.IS_FIRST_SHOW)
        trackEvent()
        registerObserver()
    }

    private fun initAppsFlyer() {
        AppsFlyer.setAfConversionListener(object : AppsFlyer.AfConversionListener {
            override fun onAttributionFailure(errorMessage: String) {
                afChannel = true
                LogUtil.i("启动页：onAttributionFailure(): $errorMessage")
            }

            override fun onConversionDataFail(errorMessage: String) {
                afChannel = true
                LogUtil.i("启动页：onConversionDataFail(): $errorMessage")
            }

            override fun onConversionDataSuccess(conversionDataMap: Map<String, Any>) {
                if (!initTopOn) {
                    val status: String =
                        Objects.requireNonNull(conversionDataMap["af_status"]).toString()
                    if (status == "Non-organic") {
                        var paramValue = conversionDataMap["media_source"]
                        if (paramValue == null) {
                            paramValue = conversionDataMap["af_channel"]
                        }
                        if (paramValue != null) {
                            val customMap: MutableMap<String, Any> = HashMap()
                            customMap["channel"] = paramValue
                            ATSDK.initCustomMap(customMap)
                        }
                        afChannel = true
//                        LogUtil.i("渠道pid：$paramValue")
                    } else {
                        val customMap: MutableMap<String, Any> = HashMap()
                        customMap["channel"] = "organic"
                        ATSDK.initCustomMap(customMap)
                    }
                }
            }
        })
        AppsFlyer.init()
    }

    private fun initFirebase() {
        setFirebaseListener()
        FireBaseUtils.init()
        LogUtil.i("初始化Firebase")
    }

    private fun trackEvent() {
        //页面展示  app_launch_show
        AppsFlyerUtils.trackEvent("app_launch_show")
//        if (!SpUtils.getBoolean("app_first_open")) {
//            //第一次展示  app_first_open
//            AppsFlyerUtils.trackEvent("app_first_open")
//            //第一次冷启动开屏
//            ATInterstitial.entryAdScenario(Constants.TOP_ON_INTER_ID, "f66471e28ce125")
//            SpUtils.saveBoolean("app_first_open", true)
//        }
    }

    private fun isColdLaunch() {
        if (isColdLaunch) {
            // 冷启动
            adOpenLaunch = AdsSwitch.getBoolean(AdsSwitch.adOpenLaunch)
//            if (BuildConfig.DEBUG) {
//                adOpenLaunch = true
//            }
            if (adOpenLaunch) {
                setSplashAdListener()
            } else {
                //冷启动不展示广告
                if (BpApplication.firebaseActivate) {
                    viewMode.insertUser(Constants.USER_ID)
                }
            }
        } else {
            // 热启动
            setSplashAdListener()
        }
    }


    /**
     * 广告加载成功->展示
     * 无广告->倒计时结束后跳转界面
     */
    private fun setSplashAdListener() {
        progressBarUpdater.cancel()
        TopOnSplashFinishObservable.registerSplash(this@BpSplashActivity)
        val intent = Intent(this@BpSplashActivity, SplashAdShowActivity::class.java)
        intent.putExtra(
            "isColdLaunch", if (isColdLaunch) {
                1
            } else {
                2
            }
        )
        startActivity(intent)
        overridePendingTransition(R.anim.fade_in, 0)

//        (application as BpApplication).showAdIfAvailable(
//            this,
//            object : OnShowAdCompleteListener {
//                override fun onShowAdComplete() {
//                    LogUtil.i("闪屏页：关闭")
//                    progressBarUpdater.simulateAnimationEnd()
////                    binding.progressBar.progress = 100
//                }
//
//                override fun onAdShowedFullScreenContent() {
//                    LogUtil.i("闪屏页：展示成功")
//                    //启动页_开屏广告展示 ad_open_launch_show
//                    AppsFlyerUtils.trackEvent("ad_open_launch_show")
//                    if (firstShow.isNullOrEmpty()) {
//                        LogUtil.i("启动页第一次展示-开屏广告展示 事件埋点")
//                        //启动页第一次展示-开屏广告展示  ad_open_first_open_show
//                        AppsFlyerUtils.trackEvent("ad_open_first_open_show")
//                        SpUtils.saveString(Constants.IS_FIRST_SHOW, "set")
//                    }
//                    progressBarUpdater.cancel()
//                }
//            })
    }

    private fun initCountDownTimer() {
        progressBarUpdater = ProgressBarUpdater(
            totalDuration = 10000,
            onUpdate = {
//                LogUtil.i("进度条：$it")
                if (_binding == null) {
                    return@ProgressBarUpdater
                }
                binding.progressBar.progress = it
                if (it % 10 == 0) {
                    checkAppsFlyer(it)
//                    if (BpApplication.adMobOpenAdManager!!.appOpenAd != null) {
                    if (TopOnOpenAdManager.isAdReady()) {
                        if (listener) {
                            listener = false
                            isColdLaunch()
                        }
                    } /*else {
                        LogUtil.i("TopOn 【开屏广告】 time: ${it/10}")
                        LogUtil.i("TopOn 【开屏广告】 isAdReady:  ${TopOnOpenAdManager.isAdReady()}")
                    }*/
                }
            },
            onAnimationEnd = {
                viewMode.insertUser(Constants.USER_ID)
                LogUtil.i("闪屏页：onAnimationEnd")
            },
        )
        progressBarUpdater.setupAnimator()
    }

    private fun checkAppsFlyer(vararg time: Int) {
        if (afChannel || time[0] > 50) {
            if (!initTopOn) {
                initTopOn = true
                LogUtil.i("开始初始化广告：afChannel=${afChannel} time=${time[0]}")
                //延迟初始化 和加载广告
                ATSDK.init(
                    BpApplication.context, Constants.TOP_ON_APP_ID, Constants.TOP_ON_APP_KEY
                )
                loadTopOnOpenAd()
                //第一次安装时请求插页广告
                if (SpUtils.getString(Constants.IS_SET_LANGUAGE).isNullOrEmpty()) {
                    loadTopOnInterAd()
                }
                TopOnNativeAdManager.initATNativeAd()
                TopOnNativeAdManager.loadAd()
            }
        }
    }

    private fun registerObserver() {
        viewMode.userBeanResult.observe(this) { user ->
            TopOnInterAdManager.setManualLoadListener(null)
            if (user != null && _binding != null) {
                binding.progressBar.progress = 100
                //通知跳心率页
                if (Constants.HEART_RATE_JUMP) {
                    Constants.HEART_RATE_JUMP = false
                    startActivity(Intent(activity, BpMainActivity::class.java))
                    startActivity(Intent(activity, BpHeartRateGuideActivity::class.java))
                } else if (Constants.BLOOD_PRESSURE_JUMP) {
                    //通知跳血压页
                    Constants.BLOOD_PRESSURE_JUMP = false
                    startActivity(Intent(activity, BpMainActivity::class.java))
                    startActivity(Intent(activity, BpBloodPressureNewRecordActivity::class.java))
                } else if (SpUtils.getString(Constants.IS_SET_LANGUAGE).isNullOrEmpty()) {
                    //启动流程去掉设置语言页
//                    startActivity(Intent(activity, BpLanguageActivity::class.java))
                    val intent = Intent(activity, GuideSplashActivity::class.java)
                    intent.putExtra("isFirstOpen", user.isFirstOpen)
                    startActivity(intent)
                } else {
                    startActivity(Intent(activity, BpMainActivity::class.java))
                }
                //已经走完引导流程，销毁当前界面
                if (SpUtils.getString(Constants.IS_SET_LANGUAGE)?.isNotBlank() == true) {
                    finish()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AppsFlyer.setAfConversionListener(null)
        FireBaseUtils.setFetchConfigCompleteCallback(null)
        TopOnInterAdManager.releaseManualLoadInterstitialAd()
        TopOnSplashFinishObservable.unRegisterSplash(this)
        if (this::progressBarUpdater.isInitialized) {
            progressBarUpdater.release()
        }
        BpApplication.adMobOpenAdManager?.releaseOpenAd()
    }

    private fun initTopOn() {
        showGDPRConsentDialog()
    }

    private fun showGDPRConsentDialog() {
        //应用上线前须关闭
//        testTopOnSdk()

        ATSDK.showGDPRConsentDialog(activity) {
            LogUtil.iTopOn("initTopOn showGDPRConsentDialog onDismiss()")
            if (!dismissUMP) {
                dismissUMP = true
                initFirebase()
//                ATSDK.init(
//                    BpApplication.context, Constants.TOP_ON_APP_ID, Constants.TOP_ON_APP_KEY
//                )
            }
        }

        //应用上线前须关闭
//        ATSDK.setDebuggerConfig(
//            this,
//            "BA5F175035216FD5293788F3B2CA5AE3",
//            ATDebuggerConfig.Builder().setUMPTestDeviceId("BA5F175035216FD5293788F3B2CA5AE3")
//                .build()
//        )
    }

    private fun showGdprAuth() {
        ATSDK.checkIsEuTraffic(this, object : NetTrafficeCallback {
            override fun onResultCallback(isEU: Boolean) {
                LogUtil.iTopOn("initTopOn onResultCallback isEU: $isEU")
                if (isEU && ATSDK.getGDPRDataLevel(BpApplication.context) == ATSDK.UNKNOWN) {
                    ATSDK.showGdprAuth(activity, object : ATGDPRAuthCallback {
                        override fun onAuthResult(level: Int) {
                            LogUtil.d("initTopOn onAuthResult level：$level")
                            ATSDK.setGDPRUploadDataLevel(activity, level)
                            initFirebase()
                            ATSDK.init(
                                BpApplication.context,
                                Constants.TOP_ON_APP_ID,
                                Constants.TOP_ON_APP_KEY
                            )
                        }

                        override fun onPageLoadFail() {
                            LogUtil.d("initTopOn onPageLoadFail")

                        }
                    })
                }
            }

            override fun onErrorCallback(errorMsg: String) {
                ATSDK.init(BpApplication.context, Constants.TOP_ON_APP_ID, Constants.TOP_ON_APP_KEY)
                initFirebase()
                LogUtil.e("initTopOn onErrorCallback: $errorMsg")
            }
        })
    }

    fun loadTopOnAd() {
        initCountDownTimer()
    }

    private fun loadTopOnOpenAd() {
        TopOnOpenAdManager.initTopOnSplashAd()
        TopOnOpenAdManager.setExListener(object : TopOnOpenAdListener {
            override fun onAdLoadTimeout() {
                LogUtil.i("TopOn 【开屏广告】 onAdLoadTimeout()")
                progressBarUpdater.simulateAnimationEnd()
            }

            override fun onNoAdError() {
                LogUtil.i("TopOn 【开屏广告】 onNoAdError()")
                progressBarUpdater.simulateAnimationEnd()
            }

            override fun onAdDismiss() {
                TopOnOpenAdManager.setExListener(null)
            }

            override fun onAdLoaded() {
                LogUtil.i("TopOn 【开屏广告】 onAdLoaded ${TopOnOpenAdManager.isAdReady()}")
            }
        })
//        TopOnOpenAdManager.loadAd()
    }

    private fun loadTopOnInterAd() {
        TopOnInterAdManager.initManualLoadInterstitialAd(this)
        TopOnInterAdManager.manualLoadAd()
    }

//    private fun testTopOnSdk() {
//        //AdMob
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(Admob_NETWORK).build()
//        )
//        //Mintegral
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(Mintegral_NETWORK).build()
//        )
//        //Vungle
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(Vungle_NETWORK).build()
//        )
//        //IronSource
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(Ironsource_NETWORK).build()
//        )
//        //Unity Ads
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(UnityAds_NETWORK).build()
//        )
//        //Pangle
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(Pangle_NETWORK).build()
//        )
//        //Bigo
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(BigoAds_NETWORK).build()
//        )
//        //Applovin
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(Applovin_NETWORK).build()
//        )
//        //InMobi
//        ATSDK.setDebuggerConfig(
//            BpApplication.context, GAID, ATDebuggerConfig.Builder(Inmobi_NETWORK).build()
//        )
//
//
////        ATSDK.integrationChecking(BpApplication.context)
////
//        ATSDK.setNetworkLogDebug(true)
////        ATDebuggerUITest.showDebuggerUI(BpApplication.context)
//    }


    override fun topOnSplashFinish(splashType: SplashType) {
        if (splashType == SplashType.TYPE_SPLASH_FINISH) {
            progressBarUpdater.simulateAnimationEnd()
        } else {
            LogUtil.iTopOn("销毁启动界面")
            finish()
        }
    }

    private fun setFirebaseListener() {
        FireBaseUtils.setFetchConfigCompleteCallback(object :
            FireBaseUtils.FetchConfigCompleteCallback {
            override fun successful(var1: Boolean) {
//                LogUtil.i("firebase init listener $var1")
                //激活失败也展示开屏
//                ATSDK.setLocalStrategyAssetPath(this@BpSplashActivity, "localStrategy");
                loadTopOnAd()
            }

            override fun notReady() {
                LogUtil.i("firebase init listener notReady")
                BpApplication.firebaseActivate = false
            }
        })
    }
}

